var Attachment = (function () {
    function Attachment(associateType, files) {
        this.associateType = associateType;
        this.files = files;
    }
    return Attachment;
}());

var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

myApp.service('uploadService',
    [
        '$http', function($http) {
            this.upload = function(attachment) {
                var fd = new FormData();
                fd.append('associateType', attachment.associateType);
                fd.append('files', attachment.files);

                return $http.post('/file/upload',
                    fd,
                    {
                        transformRequest: angular.identity,
                        headers: {
                            'Content-Type': undefined
                        }
                    });
            }
        }
    ]);

myApp.controller('myCtrl', ['$scope', 'uploadService', function ($scope, uploadService) {
    $scope.upload = function() {
        $scope.showUploadStatus = false;
        $scope.showUploadedData = false;

        var attachment = new Attachment($scope.associateType, $scope.files);

        uploadService.upload(attachment).then(function(response) { // success
                if(response.status == 200) {
                    $scope.uploadStatus = "User created sucessfully.";
                    $scope.uploadedData = response.data;
                    $scope.showUploadStatus = true;
                    $scope.showUploadedData = true;
                }
            },
            function(response) { // failure
                $scope.uploadStatus = "User creation failed with status code: " + response.status;
                $scope.showUploadStatus = true;
                $scope.showUploadedData = false;
            });
    };
}]);